import React from "react";
import {
  Input,
  Radio,
  Select,
  Tabs,
  Table,
  Button,
  Form,
  Popconfirm,
  Modal,
} from "antd";
import { getUuid, openNotificationWithIcon } from 'utils/comm';

import styles from "./Pannel.less";

import udStyles from "./StartEndDetail.less";

const { TabPane } = Tabs;
// const RadioGroup = Radio.Group;
const { Option } = Select;
const { TextArea } = Input;

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};
const formItemLayout2 = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};
@Form.create()
class StartEndDetail extends React.Component {
  openNotificationWithIcon = openNotificationWithIcon.bind(this);

  state = {
    activeKey: "1",
    label: "",
    overrideid: "",
    eventConfigData: [],
  };

  componentDidMount() {
    const { selectedModel = {}, form } = this.props;
    const { properties = {} } = (selectedModel || {}).model || {};
    const { eventConfig = [] } = properties;
    this.setState({
      eventConfigData: eventConfig,
    })
    form.setFieldsValue({ callMethod: 'async' });
  }

  // eslint-disable-next-line react/no-deprecated
  componentWillReceiveProps(nextPops) {
    const { selectedModel = {}, form } = this.props;

    if (nextPops.selectedModel.id !== selectedModel.id) {
      const { properties = {} } = (nextPops.selectedModel || {}).model || {};
      const { eventConfig = [] } = properties;
      this.setState({
        eventConfigData: eventConfig,
      })
      form.resetFields();
      form.setFieldsValue({ callMethod: 'async' });
    }
  }

  handleChange = (name, value, isEmpty = false) => {
    const obj = {};
    const newValue = value || "empty";
    obj[name] = isEmpty ? value : newValue;
    this.setState({
      ...obj,
    });
  };

  testConnection = () => {
    const { dispatch, selectedModel = {} } = this.props;
    const { properties = {} } = (selectedModel || {}).model || {};
    const configUrl =
      properties.eventConfig && JSON.stringify(properties.eventConfig) !== "{}"
        ? JSON.parse(properties.eventConfig.config).url
        : "";
    dispatch({
      type: "FlowChart/testConnection",
      payload: { url: configUrl },
    }).then(({ errCode, errMsg, datas }) => {
      if (errCode === 0 && datas) {
        this.openNotificationWithIcon("success", "", "测试连接成功");
      } else if (!datas) {
        this.openNotificationWithIcon("error", "", "测试连接失败");
      } else {
        this.openNotificationWithIcon("error", "", errMsg);
      }
    });
  };

  testEvent=()=>{
    const {
      form,
      testEvent,
    }= this.props;
    const { confirm } = Modal;
    form.validateFields((err, values) => {
      if (!err) {
        testEvent(values).then((res)=>{
          const message=res.errMsg;
          confirm({
            title: '接口返回数据',
            content:
  <Form>
    <Form.Item label="接口返回Message">
      <TextArea value={message} />
    </Form.Item>
    <Form.Item label="接口返回datas">
      <TextArea value={JSON.stringify(res.datas)} />
    </Form.Item>
  </Form>,
            okText: '确定',
            cancelText: '取消',
          });
        })
      }
  })
  };

  handleFormOk = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    const { form, selectedModel = {}, handleChangeProperties2: propsHandleChangeProperties2, checkInputUrl } = this.props;
    const handleChangeProperties2 = (...args) => {
      propsHandleChangeProperties2(...args);
      this.forceUpdate();
    };
    const { eventConfigData } = this.state;
    form.validateFields((err, values) => {
      if (!err) {
        checkInputUrl(values.config).then((res) => {
          if(res.errCode === 0) {
            this.openNotificationWithIcon("success", "", res.datas);
            if (values.key) { // 编辑
              // eslint-disable-next-line array-callback-return
              eventConfigData.map((item) => {
                if (item.key === values.key) {
                  item.name = values.name
                  item.config = { url: values.config }
                  item.eventType = values.eventType
                  item.callMethod = values.callMethod
                  item.requestBody = values.requestBody
                  item.desc = values.desc
                  item.callbackParam = values.callbackParam;
                }
              })
              this.setState({ eventConfigData })
            } else { // 新增
              values.key = getUuid();
              values.config = { url: values.config }
              eventConfigData.push(values);
              this.setState({
                eventConfigData,
              }, () => {
                handleChangeProperties2(
                  "eventConfig",
                  eventConfigData,
                  selectedModel.model,
                  selectedModel.shape,
                  false,
                );
              });
            }
          }
        })
        form.resetFields();
        form.setFieldsValue({ callMethod: 'async' });
      }
    });
  };

  handleDelete = (record) => {
    const { eventConfigData } = this.state;
    const { selectedModel = {}, handleChangeProperties2: propsHandleChangeProperties2 } = this.props;
    const handleChangeProperties2 = (...args) => {
      propsHandleChangeProperties2(...args);
      this.forceUpdate();
    };
    const newEventConfig = eventConfigData.filter((v) => v.key !== record.key);
    this.setState({ eventConfigData: newEventConfig }, () => {
      handleChangeProperties2(
        "eventConfig",
        newEventConfig,
        selectedModel.model,
        selectedModel.shape,
        false,
      );
    });
  };

  handleEdit = (record) => {
    const { form } = this.props;
    const config = record.config.url;
    form.setFieldsValue(record);
    form.setFieldsValue({ config })
  }

  render() {
    const {
      activeKey,
      label: inputingLabel,
      overrideid,
      eventConfigData,
    } = this.state;
    const {
      checkOverrideid,
      disable,
      selectedModel = {},
      handleChangeProperties: propsHandleChangeProperties,
      handleGraphChange,
      form,
    } = this.props;
    const { getFieldDecorator } = form;
    const { properties = {} } = (selectedModel || {}).model || {};

    /*
    不用设置节点的变量
    const { timeoutSetting = {}, nodeVariables = [] } = properties;

    const formatedNodeVariables = formatFormParameters(nodeVariables);
    */

    const handleChangeProperties = (...args) => {
      propsHandleChangeProperties(...args);
      this.forceUpdate();
    };

    /* const handleChangeMultiProperties = (...args) => {
      propsHandleChangeMultiProperties(...args);
      this.forceUpdate();
    } */
    const {
      // httpcallback: httpcallbackData = {},
      // description: propertyDescription = "",
      multiinstance_condition = "", // eslint-disable-line
    } = properties;
    // const {
    //   urgeStartTime = "quarterHour",
    //   urgeInterval = "quarterHour",
    // } = nodeAuth.urge;
    const labelValue =
      inputingLabel === "empty" ? "" : inputingLabel || selectedModel.label;
    // const description =
    //   descriptionLabel === "empty"
    //     ? ""
    //     : descriptionLabel || propertyDescription;
    const overrideidVal =
      overrideid === "empty" ? "" : overrideid || properties.overrideid

    const eventColumns = [
      {
        title: '事件名称',
        dataIndex: 'name',
        key: 'name',
        align: 'center',
      },
      {
        title: '事件url',
        dataIndex: 'config',
        key: 'config',
        align: 'center',
        render: (text, record) => (
          <span>
            {record.config.url}
          </span>
        ),
      },
      {
        title: '事件类型',
        dataIndex: 'eventType',
        key: 'eventType',
        align: 'center',
        render: (text, record) => {
          return <span>{record.eventType === "" ? '-' : (record.eventType === "ACTIVITY_STARTED" ? '流程前置' : "流程后置")}</span>
        },
      },
      {
        title: "操作",
        align: 'center',
        render: (text, record) => {
          return (
            <div>
              <a
                onClick={(e) => {
                  e.preventDefault();
                  this.handleEdit(record);
                }}
                style={{ marginRight: '10px' }}
              >
                编辑
              </a>
              <Popconfirm
                placement="left"
                title={`确定删除事件：${record.name}?`}
                onConfirm={() => {
                  this.handleDelete(record);
                }}
                okText="确定"
                cancelText="取消"
              >
                <a
                  onClick={(e) => {
                    e.preventDefault();
                  }}
                >
                  删除
                </a>
              </Popconfirm>
            </div>
          );
        },
      }];

    return (
      <>
        <div className={styles.headTitle}>开始/结束 节点</div>
        <div
          className={`block-container ${styles.content} ${udStyles.container}`}
        >
          <Tabs
            activeKey={activeKey}
            tabBarGutter={50}
            onChange={(key) => this.setState({ activeKey: key })}
            size="small"
          >
            <TabPane tab="基础信息" key="1">
              {/* <div className={`${styles.content_item} ${styles.hq_item}`}> */}

              <div className={styles.content_item}>
                <span className={styles.item_label}>节点名称：</span>
                <Input
                  disabled={disable}
                  placeholder="请输入"
                  maxLength={30}
                  value={labelValue}
                  onChange={(ev) => this.handleChange("label", ev.target.value)}
                  onBlur={(ev) => {
                    handleGraphChange("label", ev.target.value, false);
                    this.handleChange("label", "", true);
                    handleChangeProperties(
                      "label",
                      ev.target.value,
                      selectedModel.model,
                      selectedModel.shape,
                      false,
                    );
                  }}
                />
              </div>
              <div className={styles.content_item}>
                <span className={styles.item_label}>节点编码：</span>
                <Input
                  disabled={disable}
                  maxLength={30}
                  placeholder="请输入"

                  // eslint-disable-next-line react/jsx-props-no-multi-spaces
                  value={overrideidVal}
                  onChange={(ev) =>
                    this.handleChange("overrideid", ev.target.value)
                  }
                  onBlur={(ev) => {
                    checkOverrideid(ev);
                    this.handleChange("overrideid", "", true);
                    handleChangeProperties(
                      "overrideid",
                      ev.target.value,
                      selectedModel.model,
                      selectedModel.shape,
                      false,
                    );
                  }}
                />
              </div>
              {/* <div className={styles.content_item}>
                <span className={styles.item_label}>节点说明：</span>
                <TextArea
                  disabled={disable}
                  placeholder="请输入说明"
                  maxLength={100}
                  value={description}
                  onChange={(ev) =>
                    this.handleChange("description", ev.target.value)
                  }
                  onBlur={(ev) => {
                    handleChangeProperties(
                      "description",
                      ev.target.value,
                      selectedModel.model,
                      selectedModel.shape,
                      false,
                    );
                    this.handleChange("description", "", true);
                  }}
                />
              </div> */}
            </TabPane>
            <TabPane tab="事件" key="2">
              <Form>
                <Form.Item>
                  {getFieldDecorator("key", {
                    initialValue: "",
                  })(<Input type='hidden' />)}
                </Form.Item>
                <Form.Item label="事件名称" {...formItemLayout}>
                  {getFieldDecorator("name", {
                    initialValue: "",
                    rules: [
                      { required: true, message: "请输入事件名称" },
                    ],
                  })(<Input placeholder="请输入事件名称" />)}
                </Form.Item>
                <Form.Item label="事件url" {...formItemLayout}>
                  {getFieldDecorator("config", {
                    initialValue: "",
                    rules: [
                      { required: true, message: "请输入事件url" },
                    ],
                  })(<Input placeholder="请输入事件url" />)}
                </Form.Item>
                <Form.Item label="requestBody" {...formItemLayout}>
                  {getFieldDecorator("requestBody", {
                    initialValue: "",
                  })(<TextArea
                    rows={4}
                    // eslint-disable-next-line no-template-curly-in-string
                    placeholder='{ &#13;&#10;
                    "流程实例Id":"${_processInstanceId}",&#13;&#10;
                    "发起人Id":"${_applyUserId}" &#13;&#10;
                  }'
                  />)}
                </Form.Item>
                <Form.Item label="事件触发时机" {...formItemLayout}>
                  {getFieldDecorator('eventType', {
                    initialValue: "",
                  })(
                    <Select placeholder="请选择事件触发时机">
                      <Option value="ACTIVITY_STARTED">流程前置</Option>
                      <Option value="ACTIVITY_COMPLETED">流程后置</Option>
                    </Select>,
                  )}
                </Form.Item>
                <Form.Item label="        " {...formItemLayout2} colon={false}>
                  {getFieldDecorator('callMethod', {
                    initialValue: "async",
                  })(
                    <Radio.Group>
                      <Radio value="sync">同步</Radio>
                      <Radio value="async">异步</Radio>
                    </Radio.Group>,
                  )}
                </Form.Item>
                <Form.Item label="事件备注" {...formItemLayout}>
                  {getFieldDecorator("desc", {
                    initialValue: "",
                  })(<TextArea maxLength={200} rows={4} placeholder="请输入事件备注" />)}
                </Form.Item>
                <Form.Item label="回调参数" {...formItemLayout}>
                  {getFieldDecorator("callbackParam", {
                    initialValue: "",
                  })(<Input placeholder="请输入回调参数" />)}
                </Form.Item>
                <Form.Item>
                  <Button onClick={this.testEvent} style={{ float: 'left' }}>
                    测试
                  </Button>
                  <Button type="primary" onClick={this.handleFormOk} style={{ float: 'right' }}>
                    添加
                  </Button>
                </Form.Item>
              </Form>
              <Table
                style={{ width: '350px' }}
                bordered
                columns={eventColumns}
                dataSource={eventConfigData}
                pagination={false}
              // scroll={{y:300}}
              />
            </TabPane>
          </Tabs>
        </div>
      </>
    );
  }
}
export default StartEndDetail;
